package constant.milk.cashbook.photo;

import java.io.IOException;

import constant.milk.cashbook.util.MilkUtil;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MintSurfaceView extends SurfaceView implements
		SurfaceHolder.Callback
{
	private SurfaceHolder surfaceHolder;
	private Camera camera;

	public MintSurfaceView(Context context)
	{
		super(context);

		surfaceHolder = getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	public boolean setPhoto(Camera.PictureCallback handler)
	{
		if (camera != null)
		{
			camera.takePicture(new ShutterCallback()
			{
				@Override
				public void onShutter()
				{
				}
			}, new PictureCallback()
			{
				@Override
				public void onPictureTaken(byte[] data, Camera camera)
				{
				}
			}, handler);

			return true;
		} else
		{
			return false;
		}
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height)
	{
		Camera.Parameters parameters = camera.getParameters();
		
		parameters.setFocusMode(Parameters.FOCUS_MODE_MACRO);
		camera.setParameters(parameters);
		
		camera.startPreview();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder)
	{
		try
		{
			if (camera == null)
			{
				camera = Camera.open();
			}

			if (camera != null)
			{
				camera.setPreviewDisplay(surfaceHolder);
			}
		} catch (IOException e)
		{
			e.printStackTrace();

			if (camera != null)
			{
				camera.stopPreview();
				camera.release();
				camera = null;
			}
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		if (camera != null)
		{
			camera.stopPreview();
			camera.release();
			camera = null;
		}
	}
	
	public void closeUp()
	{
		Camera.Parameters parameters = camera.getParameters();
		
		parameters.setFocusMode(Parameters.FOCUS_MODE_MACRO);
		camera.setParameters(parameters);
	}
	
	public void closeDown()
	{
		Camera.Parameters parameters = camera.getParameters();
		
		parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
		camera.setParameters(parameters);
	}
}
